<?php


if (!function_exists('fill_created_by')) {
    /**
     * 填充当前用户id
     * @return mixed
     */
    function fill_created_by()
    {
        return \request()->getUserId();
    }
}

if (!function_exists('auto_fill_default_id')) {
    /**
     * 自动填充默认ID
     * @param array $data
     * @param string $field
     * @return mixed
     */
    function auto_fill_default_id($data = [], $field = '')
    {
        if (!array_key_exists($field, $data)) {
            return 0;
        }

        return $data[$field];
    }
}


if (!function_exists('auto_fill_tenant_id')) {
    /**
     * 自动填充租户ID
     * @return int
     */
    function auto_fill_tenant_id()
    {
        return \request()->getTenantId();
    }
}


if (!function_exists('auto_fill_tenant_id_with_data')) {
    /**
     * 自动填充租户ID (支持外部覆盖字段)
     * @return int
     */
    function auto_fill_tenant_id_with_data($data, $field)
    {
        if (array_key_exists($field, $data) && $data[$field] > 0) {
            return $data[$field];
        }
        return \request()->getTenantId();
    }
}


if (!function_exists('string_is_component')) {
    /**
     * 判断字符串是否为纯字母
     * @param $str
     * @return bool
     */
    function string_is_component($str)
    {
        if (preg_match("/^[A-Za-z]/", $str)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('array_to_json')) {
    /**
     * 把数组转换成Json
     * @param $arr
     * @return string
     */
    function array_to_json($arr)
    {
        if (is_array($arr)) {
            $res_arr = json_encode($arr);
        } else {
            $res_arr = $arr;
        }
        return $res_arr;
    }
}

if (!function_exists('is_json')) {
    /**
     * 检测元素是否为json
     * @param $string
     * @return bool
     */
    function is_json($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }
}

if (!function_exists('check_array_unique')) {
    /**
     * 判断数组是否为有重复元素
     * @param $arr
     * @return bool
     */
    function check_array_unique($arr)
    {
        if (count($arr) != count(array_unique($arr))) {
            return false;
        } else {
            return true;
        }
    }
}

if (!function_exists('check_array_dimension')) {
    /**
     * 判断数组为一维数组还是二维数组
     * @param $arr
     * @return bool
     */
    function check_array_dimension($arr)
    {
        if (count($arr) == count($arr, 1)) {
            return false;
        } else {
            return true;
        }
    }
}

if (!function_exists('check_is_relation_create')) {
    /**
     * 判断数组为一维数组还是二维数组
     * @param $arr
     * @return bool
     */
    function check_is_relation_create($arr)
    {
        foreach ($arr as $key => $data) {
            if (is_array($data) && check_array_dimension($data) && !in_array($key, ['config', 'json', 'node_config', 'param'])) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('check_cc_number')) {
    /**
     * 自动验证,检测cc是否超过6个
     * @param string
     * @return bool
     */
    function check_cc_number($cc)
    {
        $cc_arr = explode(',', $cc);
        if (count($cc_arr) > 6) {
            return false;
        } else {
            return true;
        }
    }
}

if (!function_exists('create_pass')) {
    /**
     * 加密密码
     * @param string $password
     * @return bool|string
     */
    function create_pass($password = "")
    {
        if (!empty($password)) {
            $options = [
                'cost' => 4,
            ];
            return password_hash($password, PASSWORD_BCRYPT, $options);
        } else {
            return '';
        }
    }
}

if (!function_exists('check_pass')) {
    /**
     * 验证密码
     * @param $password
     * @param $encryptionPassword
     * @return bool
     */
    function check_pass($password, $encryptionPassword)
    {
        return password_verify($password, $encryptionPassword);

    }
}

if (!function_exists('check_login_is_email')) {
    /**
     * 判断登录名是否是邮箱地址
     * @param $login
     * @return bool
     */
    function check_login_is_email($login)
    {
        $checkmail = '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/';
        if (preg_match($checkmail, $login)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('_encrypt')) {
    /**
     * 简单对称加密算法之加密
     * @param String $string 需要加密的字串
     * @param Bool $isarry 是否是数组
     * @param String $skey 加密EKY
     * @return String
     */
    function _encrypt($string = '', $isarry = false, $skey = null)
    {
        $skey = $skey === null ? C('COOKIE_KEY') : $skey;
        $string = $isarry === true ? json_encode($string) : $string;
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value) {
            $key < $strCount && $strArr[$key] .= $value;
        }
        return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
    }
}

if (!function_exists('_decrypt')) {
    /**
     * 简单对称加密算法之解密
     * @param String $string 需要解密的字串
     * @param Bool $isarry 是否是数组
     * @param String $skey 解密KEY
     * @return String
     */
    function _decrypt($string = '', $isarry = false, $skey = null)
    {
        try {
            $skey = $skey === null ? C('COOKIE_KEY') : $skey;
            $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
            $strCount = count($strArr);
            foreach (str_split($skey) as $key => $value) {
                //$key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
                if ($key <= $strCount && array_key_exists($key, $strArr)) {
                    if (strlen($strArr[$key]) === 2 && $strArr[$key][1] === $value) {
                        $strArr[$key] = $strArr[$key][0];
                    } else {
                        throw new \Exception("error", \support\ErrorCode::DECRYPTION_FAILED);
                    }
                } else {
                    throw new \Exception("error", \support\ErrorCode::DECRYPTION_FAILED);
                }

            }
            $decode = base64_decode(join('', $strArr));
            $decode = $isarry === true ? json_decode($decode, true) : $decode;
        } catch (\Exception $e) {
            $decode = [];
        }
        return $decode;
    }
}

if (!function_exists('get_lang_type')) {
    /**
     * 返回语言包类型
     * @param string
     * @return string
     */
    function get_lang_type($lang)
    {
        switch ($lang) {
            case 'zh-cn':
                $lang_type = 'zh-cn';
                break;
            case 'en-us':
                $lang_type = 'en-us';
                break;
            default:
                $lang_type = 'en-us';
        }
        return $lang_type;
    }
}

if (!function_exists('is_today')) {
    /**
     * 判断日期是否为今天
     * @param $date
     * @return int
     */
    function is_today($date)
    {
        $c_date = date('Y-m-d', $date);
        $today = date('Y-m-d');
        if ($c_date == $today) {
            return 1;
        } else {
            return 0;
        }
    }
}

if (!function_exists('is_hurry_date')) {
    /**
     * 判断任务截至日期是否在捉急
     * @param $date
     * @param $days
     * @return string
     */
    function is_hurry_date($date, $days)
    {
        $section = $days * 86400;
        $now = time();
        $cnow = $date + $section;
        if ($cnow < $now) {
            $isHurry = 'hurry';
        } else {
            $isHurry = 'nohurry';
        }
        return $isHurry;
    }
}

if (!function_exists('remove_file_suffix')) {
    /**
     * 去除文件名后缀
     * @param $filename
     * @return string
     */
    function remove_file_suffix($filename)
    {
        $FileExt = substr(strrchr($filename, '.'), 1);
        $newName = basename($filename, "." . $FileExt);
        return $newName;
    }
}

if (!function_exists('create_base64_Img')) {
    /**
     * base64图片保存到临时路径
     * @param $img
     * @param $tpye
     * @return mixed
     * @throws Exception
     */
    function create_base64_Img($img, $tpye)
    {
        $fileNameRandom = string_random(8) . time(); //产生一个随机文件名
        $resData = fill_imgfile_content($img, $tpye, $fileNameRandom);
        return $resData["full_path"];
    }
}

if (!function_exists('create_temp_img')) {
    /**
     * 创建临时图片文件
     * @param $img
     * @param $tpye
     * @return array
     * @throws Exception
     */
    function create_temp_img($img, $tpye)
    {
        $baseName = string_random(8) . time();
        $fileNameRandom = $baseName . "_temp"; //产生一个随机文件名
        $resData = fill_imgfile_content($img, $tpye, $fileNameRandom);
        $resData["base_name"] = $baseName;
        return $resData;
    }
}

if (!function_exists('fill_imgfile_content')) {
    /**
     * 保存图片Base64图片
     * @param $img
     * @param $tpye
     * @param $fileNameRandom
     * @return array
     */
    function fill_imgfile_content($img, $tpye, $fileNameRandom)
    {
        //图片解码
        $base64Body = substr(strstr($img, ','), 1);
        $data = base64_decode($base64Body);
        //生成上传路径
        $imageSERVER = $_SERVER['DOCUMENT_ROOT'];
        $fileName = $imageSERVER . __ROOT__ . "/uploads/temp/" . $fileNameRandom . '.' . $tpye;
        file_put_contents($fileName, $data);
        $response = array(
            "full_path" => $fileName,
            "file_name" => $fileNameRandom,
            "ext" => $tpye
        );
        return $response;
    }
}

if (!function_exists('transcode_to_base64_Img')) {
    /**
     * 读取图片文件，转换成base64编码格式
     * @param $image
     * @return string
     */
    function transcode_to_base64_Img($image)
    {
        $IMG_SERVER = $_SERVER['DOCUMENT_ROOT'];
        $image_file = $IMG_SERVER . '/' . $image;
        $image_info = getimagesize($image_file);
        $base64_image = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
        return $base64_image;
    }
}

if (!function_exists('string_random')) {
    /**
     * 随机字符串加数字
     * @param $length
     * @return string
     * @throws Exception
     */
    function string_random($length)
    {
        $int = $length / 2;
        $bytes = random_bytes($int);
        $string = bin2hex($bytes);
        return $string;
    }
}

if (!function_exists('create_sms_code')) {
    /**
     * 生成短信验证码
     * @param int $length
     * @return int
     */
    function create_sms_code($length = 6)
    {
        $min = pow(10, ($length - 1));
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }
}

if (!function_exists('random_hash_keys')) {
    /**
     * secret key 密钥生成 32位
     * @param $string
     * @param $created
     * @return string
     * @throws Exception
     */
    function random_hash_keys($string, $created)
    {
        $data = $string . $created . string_random(10);
        $key = hash('md5', $data);
        return $key;
    }
}

if (!function_exists('string_wordwrap')) {
    /**
     * 按照指定长度对字符串进行折行处理
     * @param $string
     * @param $Length
     * @return string
     */
    function string_wordwrap($string, $Length)
    {
        $Arry = explode(" ", $string);
        $NewString = '';
        foreach ($Arry as $Line) {
            if (strlen($Line) > $Length)
                $NewString .= wordwrap($Line, $Length, " ", true);
            else
                $NewString .= " " . $Line;
        }
        return $NewString;
    }
}

if (!function_exists('list_sort_by')) {
    /**
     * 对查询结果集进行排序，asc正向排序 desc逆向排序 nat自然排序
     * @access public
     * @param array $list 查询结果
     * @param string $field 排序的字段名
     * @param array $sortby 排序类型
     * @return array|bool
     */
    function list_sort_by($list, $field, $sortby = 'asc')
    {
        if (is_array($list)) {
            $refer = $resultSet = array();
            foreach ($list as $i => $data)
                $refer[$i] = &$data[$field];
            switch ($sortby) {
                case 'asc': // 正向排序
                    asort($refer);
                    break;
                case 'desc':// 逆向排序
                    arsort($refer);
                    break;
                case 'nat': // 自然排序
                    natcasesort($refer);
                    break;
            }
            foreach ($refer as $key => $val)
                $resultSet[] = &$list[$key];
            return $resultSet;
        }
        return false;
    }
}

if (!function_exists('convert_select_data')) {
    /**
     * 转换二维数组为一维数组
     * @param $field
     * @param $array
     * @param string $indexKey
     * @return array
     */
    function convert_select_data($field, $array, $indexKey = '')
    {
        $convertData = [];
        if (!empty($indexKey)) {
            $useIndexKey = $indexKey;
        } else {
            $useIndexKey = $field;
        }
        foreach ($array as $item) {
            array_push($convertData, $item[$useIndexKey]);
        }
        return $convertData;
    }
}

if (!function_exists('unique_arr')) {
    /**
     * 去除数组重复
     * @param $filterData
     * @return array
     */
    function unique_arr($filterData)
    {
        $filterData = array_flip(array_flip($filterData));
        $newFilterData = array();
        foreach ($filterData as $k => $v) {
            if ($v == '') {
                unset($filterData[$k]);
            }
            $newFilterData[] = $filterData[$k];
        }
        return $newFilterData;
    }
}

if (!function_exists('batch_handle_data')) {
    /**
     * 批量更新数据预处理
     * @param $upData
     * @return array
     */
    function batch_handle_data($upData)
    {
        $innateData = array();
        $customData = array();
        foreach ($upData as $value) {
            switch ($value["part"]) {
                case "innate":
                    $innateData[$value["field"]] = $value["value"];
                    break;
                case "custom":
                    switch ($value["edit"]) {
                        case 20://datebox
                            $pval = strtotime($value["value"]);
                            break;
                        default:
                            $pval = $value["value"];
                            break;
                    }
                    $temp = array(
                        "fid" => $value["fid"],
                        "alias" => $value["field"],
                        "value" => $pval,
                        "edit" => $value["edit"],
                        "pos" => "batch",
                    );
                    array_push($customData, $temp);
                    break;
            }
        }
        $response = array(
            "innate" => $innateData,
            "custom" => $customData,
        );
        return $response;
    }
}

if (!function_exists('intval_string')) {
    /**
     * 强制转换字符串为整型, 对数字或数字字符串无效
     * @param mixed
     */
    function intval_string(&$value)
    {
        if (!is_numeric($value)) {
            $value = intval($value);
        }
    }
}

if (!function_exists('create_uuid')) {
    /**
     * 生成uuid
     * @return mixed
     * @throws Exception
     */
    function create_uuid()
    {
        if (function_exists("uuid_create")) {
            return uuid_create();
        } else {
            return Webpatser\Uuid\Uuid::generate()->string;
        }
    }
}

if (!function_exists('fill_text_default_val')) {
    /**
     * 填充mysql文本类型字段默认值
     * @param $value
     * @return string
     */
    function fill_text_default_val($value = '')
    {
        if (!isset($value)) {
            return '';
        }
        return $value;
    }
}

if (!function_exists('version_format')) {
    /**
     * 格式化版本号
     * @param $version
     * @return string
     */
    function version_format($version)
    {
        if (!strpos($version, 'V')) {
            return "V" . sprintf("%03d", $version);
        } else {
            return $version;
        }
    }
}

if (!function_exists('get_date_group_md5')) {
    /**
     * 获取时间md5
     * @param $date
     * @param bool $is_full
     * @return string
     */
    function get_date_group_md5($date, $is_full = false)
    {
        if ($is_full) {
            return md5($date);
        } else {
            $dateFormat = date('Y-m-d', strtotime($date));
            return md5($dateFormat);
        }
    }
}

if (!function_exists('string_initial_letter')) {
    /**
     * 下划线单个字母大写返回分隔符自定义
     * @param $string
     * @param string $prefix
     * @return string
     */
    function string_initial_letter($string, $prefix = '')
    {
        if (strpos($string, '_')) {
            $stringArray = explode('_', $string);
            $doneString = [];
            foreach ($stringArray as $item) {
                array_push($doneString, ucfirst($item));
            }
            return join($prefix, $doneString);
        } else {
            return ucfirst($string);
        }
    }
}

if (!function_exists('camelize')) {
    /**
     *  下划线转驼峰
     * 思路:
     * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
     * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
     * @param $unCamelizeWords
     * @param string $separator
     * @return string
     */
    function camelize($unCamelizeWords, $separator = '_')
    {
        $unCamelizeWords = $separator . str_replace($separator, " ", strtolower($unCamelizeWords));
        return str_replace(" ", "", ucwords(ltrim($unCamelizeWords, $separator)));
    }
}

if (!function_exists('to_under_score')) {
    /**
     * 驼峰命名转下划线命名
     * @param $str
     * @return string
     */
    function to_under_score($str)
    {
        $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
            return '_' . strtolower($matchs[0]);
        }, $str);
        return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
    }
}

if (!function_exists('get_table_name')) {
    /**
     * 获取table名称
     * @param $code
     * @return string
     */
    function get_table_name($code)
    {
        return ucwords(camelize($code));
    }
}

if (!function_exists('create_directory')) {
    /**
     * 判断目录是否存在,不存在则创建
     * @param $path
     * @param $mode
     * @return string
     */
    function create_directory($path, $mode = 0777)
    {
        if (is_dir($path)) {
            //判断目录存在否，存在不创建
            return "目录'" . $path . "'已经存在";
            //已经存在则输入路径
        } else { //不存在则创建目录
            $re = mkdir($path, $mode, true);
            //第三个参数为true即可以创建多极目录
            if ($re) {
                return "目录创建成功";
            } else {
                return "目录创建失败";
            }
        }
    }
}

if (!function_exists('delete_directory')) {
    /**
     * 删除指定目录下所有文件及其本身
     * @param $dir
     * @return bool
     */
    function delete_directory($dir)
    {
        if (!file_exists($dir)) {
            return true;
        }
        if (!is_dir($dir)) {
            return unlink($dir);
        }
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') {
                continue;
            }
            if (!delete_directory($dir . DIRECTORY_SEPARATOR . $item)) {
                return false;
            }
        }
        return rmdir($dir);
    }
}

if (!function_exists('empty_folder')) {
    /**
     * 删除指定目录下的文件，不删除目录文件夹
     * @param $dir
     */
    function empty_folder($dir)
    {
        //删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    empty_folder($fullpath);
                }
            }
        }
        closedir($dh);
    }
}

if (!function_exists('bath_empty_file_content')) {
    /**
     * 清空指定目录下的文件内容，不删除目录文件夹
     * @param $dir
     */
    function bath_empty_file_content($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullPath = $dir . "/" . $file;
                if (!is_dir($fullPath)) {
                    file_put_contents($fullPath, "");
                } else {
                    bath_empty_file_content($fullPath);
                }
            }
        }
        closedir($dh);
    }
}

if (!function_exists('get_directory_size')) {
    /**
     * 文件夹大小
     * @param $dir
     * @return int
     */
    function get_directory_size($dir)
    {
        $handle = opendir($dir);
        if (empty($sizeResult)) {
            $sizeResult = 0;
        }
        while (false !== ($FolderOrFile = readdir($handle))) {
            if ($FolderOrFile != "." && $FolderOrFile != "..") {
                if (is_dir("$dir/$FolderOrFile")) {
                    $sizeResult += get_directory_size("$dir/$FolderOrFile");
                } else {
                    $sizeResult += filesize("$dir/$FolderOrFile");
                }
            }
        }
        closedir($handle);
        return $sizeResult;
    }
}

if (!function_exists('get_week')) {
    /**
     * 获取星期方法
     * @param $time
     * @return mixed
     */
    function get_week($time)
    {
        $weekArray = array("sun", "mon", "tue", "wed", "thu", "fri", "sat");
        return $weekArray[date('w', $time)];
    }
}

if (!function_exists('date_friendly')) {
    /**
     * 时间友好型提示风格化（即微博中的XXX小时前、昨天等等）
     * 即微博中的 XXX 小时前、昨天等等, 时间超过 $time_limit 后返回按 out_format 的设定风格化时间戳
     * @param string
     * @param int
     * @param int
     * @param string
     * @param array
     * @param int
     * @return string
     *
     */
    function date_friendly($time_style, $timestamp, $time_limit = 604800, $out_format = 'Y-m-d H:i', $formats = null, $time_now = null)
    {
        if ($time_style == 'N') {
            return date($out_format, $timestamp);
        }

        if (!$timestamp) {
            return false;
        }

        if ($formats == null) {
            $formats = array('YEAR' => '%s years ago',
                'MONTH' => '%s month before',
                'DAY' => '%s days ago',
                'HOUR' => '%s hours ago',
                'MINUTE' => '%s minutes before',
                'SECOND' => '%s ago'
            );
        }

        $time_now = $time_now == null ? time() : $time_now;
        $seconds = $time_now - $timestamp;

        if ($seconds == 0) {
            $seconds = 1;
        }

        if (!$time_limit or $seconds > $time_limit) {
            return date($out_format, $timestamp);
        }

        $minutes = floor($seconds / 60);
        $hours = floor($minutes / 60);
        $days = floor($hours / 24);
        $months = floor($days / 30);
        $years = floor($months / 12);

        if ($years > 0) {
            $diffFormat = 'YEAR';
        } else {
            if ($months > 0) {
                $diffFormat = 'MONTH';
            } else {
                if ($days > 0) {
                    $diffFormat = 'DAY';
                } else {
                    if ($hours > 0) {
                        $diffFormat = 'HOUR';
                    } else {
                        $diffFormat = ($minutes > 0) ? 'MINUTE' : 'SECOND';
                    }
                }
            }
        }

        $dateDiff = null;

        switch ($diffFormat) {
            case 'YEAR' :
                $dateDiff = sprintf($formats[$diffFormat], $years);
                break;
            case 'MONTH' :
                $dateDiff = sprintf($formats[$diffFormat], $months);
                break;
            case 'DAY' :
                $dateDiff = sprintf($formats[$diffFormat], $days);
                break;
            case 'HOUR' :
                $dateDiff = sprintf($formats[$diffFormat], $hours);
                break;
            case 'MINUTE' :
                $dateDiff = sprintf($formats[$diffFormat], $minutes);
                break;
            case 'SECOND' :
                $dateDiff = sprintf($formats[$diffFormat], $seconds);
                break;
        }
        return $dateDiff;
    }
}

if (!function_exists('get_current_week_range')) {
    /**
     * 获取当前时间所在星期的开始时间与结束时间戳
     * @return array
     */
    function get_current_week_range()
    {
        $ret = array();
        $timestamp = mktime(0, 0, 0);
        $w = strftime('%u', $timestamp);
        $ret['sdate'] = $timestamp - ($w - 1) * 86400;
        $ret['edate'] = strtotime('+1 day', $timestamp + (7 - $w) * 86400 - 1);
        return $ret;
    }
}

if (!function_exists('get_current_day_range')) {
    /**
     * 获取当前时间所在天的开始时间与结束时间戳
     * @param $timestamp
     * @return array
     */
    function get_current_day_range($timestamp)
    {
        $ret = array();
        $ret['sdate'] = strtotime(date('Y-m-d', $timestamp));
        $ret['edate'] = $ret['sdate'] + 86399;
        return $ret;
    }
}

if (!function_exists('get_current_week_each_day')) {
    /**
     * 获取当前时间所在星期的每天时间戳
     * @return array
     */
    function get_current_week_each_day()
    {
        $ret = array();
        $timestamp = mktime(0, 0, 0);
        $w = strftime('%u', $timestamp);
        $ret['Mon'] = $timestamp - ($w - 1) * 86400;
        $ret['Tue'] = $timestamp - ($w - 2) * 86400;
        $ret['Wed'] = $timestamp - ($w - 3) * 86400;
        $ret['Thu'] = $timestamp - ($w - 4) * 86400;
        $ret['Fri'] = $timestamp - ($w - 5) * 86400;
        $ret['Sta'] = $timestamp - ($w - 6) * 86400;
        $ret['Sun'] = $timestamp - ($w - 7) * 86400;
        $ret['sdate'] = $ret['Mon'];
        $ret['edate'] = strtotime('+1 day', $ret['Sun'] - 1);
        return $ret;
    }
}

if (!function_exists('get_week_time_range')) {
    /**
     * 获取指定日期所在星期的开始时间与结束时间(时间戳)
     * @param $date
     * @return array
     */
    function get_week_time_range($date)
    {
        $ret = array();
        $timestamp = strtotime($date . " 00:00:00");
        $w = strftime('%u', $timestamp);
        $ret['sdate'] = $timestamp - ($w - 1) * 86400;
        $ret['edate'] = $timestamp + (7 - $w) * 86400;
        return $ret;
    }
}

if (!function_exists('get_week_range')) {
    /**
     * 获取指定日期所在星期的开始时间与结束时间
     * @param $date
     * @return array
     */
    function get_week_range($date)
    {
        $ret = array();
        $timestamp = strtotime($date);
        $w = strftime('%u', $timestamp);
        $ret['sdate'] = date('Y-m-d 00:00:00', $timestamp - ($w - 1) * 86400);
        $ret['edate'] = date('Y-m-d 23:59:59', $timestamp + (7 - $w) * 86400);
        return $ret;
    }
}

if (!function_exists('get_month_range')) {
    /**
     * 获取指定日期所在月的开始日期与结束日期
     * @param $date
     * @return array
     */
    function get_month_range($date)
    {
        $ret = array();
        $timestamp = strtotime($date);
        $mdays = date('t', $timestamp);
        $ret['sdate'] = date('Y-m-1 00:00:00', $timestamp);
        $ret['edate'] = date('Y-m-' . $mdays . ' 23:59:59', $timestamp);
        return $ret;
    }
}

if (!function_exists('get_month_time')) {
    /**
     * 获取指定日期所在月的开始日期与结束日期(时间戳)
     * @param $date
     * @return array
     */
    function get_month_time($date)
    {
        $ret = array();
        $timestamp = strtotime($date);
        $mdays = date('t', $timestamp);
        $ret['sdate'] = strtotime(date('Y-m-1 00:00:00', $timestamp));
        $ret['edate'] = strtotime(date('Y-m-' . $mdays . ' 23:59:59', $timestamp));
        return $ret;
    }
}

if (!function_exists('get_month_weeks')) {
    /**
     * 获得一个月有多少周
     * @param $month
     * @return array
     */
    function get_month_weeks($month)
    {
        $weekInfo = array();
        $end_date = date('d', strtotime($month . ' +1 month -1 day'));
        for ($i = 1; $i < $end_date; $i = $i + 7) {
            $w = date('N', strtotime($month . '-' . $i));
            $weekInfo[] = array(date('Y-m-d', strtotime($month . '-' . $i . ' -' . ($w - 1) . ' days')), date('Y-m-d', strtotime($month . '-' . $i . ' +' . (7 - $w) . ' days')));
        }
        return $weekInfo;
    }
}

if (!function_exists('get_interval_month')) {
    /**
     * 获取当前时间之后第N个自然月最后一天的日期(时间戳)
     * @param $time
     * @param $num
     * @return false|int
     */
    function get_interval_month($time, $num)
    {
        $result_day = "";
        $start = intval(date("m", $time));
        for ($i = 0; $i < $num; $i++) {
            if (($start + $i) > 12) {
                $result_day = date("Y-" . (($start + $i) - 12) . "-01", strtotime("+1 year"));
            } else {
                $result_day = date("Y-" . ($start + $i) . "-01", $time);
            }
            $day = date("t", strtotime($result_day));
            $result_day = date("Y-m-d 23:59:59", (strtotime($result_day) + ($day - 1) * 24 * 3600));
        }
        $result_time = strtotime($result_day) + 1;
        return $result_time;
    }
}

if (!function_exists('get_all_month')) {
    /**
     * 获得某个时间段内，所有的自然月
     * @param array $data
     * @return array
     */
    function get_all_month(array $data)
    {
        $firstDate = $data[0];
        $lastDate = $data[1];
        $start = intval(date("m", strtotime($firstDate)));
        $end = intval(date("m", strtotime($lastDate)));
        $result = array();
        for ($i = $start; $i <= $end; $i++) {
            $firstDay = date("Y-" . $i . "-01", strtotime($firstDate));
            $lastDay = date("Y-m-d", strtotime("$firstDay +1 month -1 day"));
            array_push($result, array('firstday' => $i == $start ? $firstDate : $firstDay, 'lastday' => $i == $end ? $lastDate : $lastDay));
        }
        return $result;
    }
}

if (!function_exists('get_weekend_days')) {
    /**
     * 给定日期之间的周末天数
     * @param $startDate
     * @param $endDate
     * @param bool $isWorkday
     * @return float|int
     */
    function get_weekend_days($startDate, $endDate, $isWorkday = false)
    {
        if (strtotime($startDate) > strtotime($endDate)) {
            list($startDate, $endDate) = array($endDate, $startDate);
        };
        $endAdd = 0;
        $startN = date('N', strtotime($startDate));
        $startReduce = ($startN == 7) ? 1 : 0;
        $endN = date('N', strtotime($endDate));
        in_array($endN, array(6, 7)) && $endAdd = ($endN == 7) ? 2 : 1;
        $allDays = abs(strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
        $weekendDays = floor(($allDays + $startN - 1 - $endN) / 7) * 2 - $startReduce + $endAdd;
        if ($isWorkday) {
            $workdayDays = $allDays - $weekendDays;
            return $workdayDays;
        }
        return $weekendDays;
    }
}

if (!function_exists('get_year_time')) {
    /**
     * 获取指定日期所在年的开始日期与结束日期(时间戳)
     * @param $date
     * @return array
     */
    function get_year_time($date)
    {
        $year = date("Y", strtotime($date));
        $ret = array();
        $ret["sdate"] = strtotime($year . "-01-01 00:00:00");
        $ret["edate"] = strtotime($year . "-12-31 23:59:59") + 1;
        return $ret;
    }
}

if (!function_exists('year_month_list')) {
    /**
     * 一年月份
     * @param $month
     * @return array
     */
    function year_month_list($month)
    {
        switch ($month) {
            case 1:
                return [
                    "id" => 1,
                    "name" => '请选择'
                ];
            default:
                return [
                    "id" => $month,
                    "name" => ($month / 10) . 'month'
                ];
        }
    }
}

if (!function_exists('validate_date_format')) {
    /**
     * 判断是否是合法日期
     * @param $date
     * @param string $format
     * @return bool
     */
    function validate_date_format($date, $format = 'Y-m-d')
    {
        $d = DateTime::createFromFormat($format, $date);
        return $d && $d->format($format) == $date;
    }
}

if (!function_exists('is_timestamp')) {
    /**
     * 判断是不是时间戳
     * @param $timestamp
     * @return bool
     */
    function is_timestamp($timestamp)
    {
        $check = (is_int($timestamp) or is_float($timestamp))
            ? $timestamp
            : (string)(int)$timestamp;
        return ($check === $timestamp)
            and ((int)$timestamp <= PHP_INT_MAX)
            and ((int)$timestamp >= ~PHP_INT_MAX);
    }
}

if (!function_exists('get_progress_color')) {
    /**
     * 获取Progress 颜色
     * @param $progress
     * @return string
     */
    function get_progress_color($progress)
    {
        $color = "";
        switch ($progress) {
            case 'blocked'://Blocked 暂停 #e94310 红色
                $color = 'e94310';
                break;
            case 'not_started'://NotStarted 未开始 #cacaca 灰色
                $color = 'cacaca';
                break;
            case 'in_progress'://InProgress 进行中 #11b0e9 蓝色
                $color = '11b0e9';
                break;
            case 'daily'://Daily 审片  #23ddeb 淡蓝色
                $color = '23ddeb';
                break;
            case 'feedback'://Feedback 反馈  #faad14 橙色
                $color = 'faad14';
                break;
            case 'done'://Done 完成  #afd440 绿色
                $color = 'afd440';
                break;
            case 'hide'://Hide 隐藏  #000000 黑色
                $color = '000000';
                break;
        }
        return $color;
    }
}

if (!function_exists('two_dimension_sort')) {
    /**
     * 二维数组根据键值排序, 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
     * @param $arr
     * @param $sort
     * @param $v
     * @return mixed
     */
    function two_dimension_sort($arr, $sort, $v)
    {
        if ($sort == "0") {
            $sort = "SORT_ASC";
        } elseif ($sort == "1") {
            $sort = "SORT_DESC";
        }
        foreach ($arr as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrsort[$key][$uniqid] = $value;
            }
        }
        if ($sort) {
            array_multisort($arrsort[$v], constant($sort), $arr);
        }
        return $arr;
    }
}

if (!function_exists('get_user_timezone_inter')) {
    /**
     * 获取当前用户所在时差
     * @return int|mixed
     */
    function get_user_timezone_inter()
    {
        return C("default_timezone_custom");
    }
}

if (!function_exists('get_format_date')) {
    /**
     * string格式化用户使用语言
     * @param $time
     * @param int $type
     * @param bool $isGantt
     * @return false|string
     */
    function get_format_date($time, $type = 0, $isGantt = false)
    {
        if (!empty($time) && is_numeric($time)) {
            $inter = get_user_timezone_inter();

            $timestamp = $time + (3600 * $inter);

            switch ($type) {
                case 0:
                    if ($isGantt) {
                        $date = gmdate("d-m-Y", $timestamp);
                    } else {
                        $date = gmdate("Y-m-d", $timestamp);
                    }
                    break;
                case 2:
                    $date = gmdate("Y-m-d H:i", $timestamp);
                    break;
                case 1:
                default:
                    $date = gmdate("Y-m-d H:i:s", $timestamp);
                    break;
            }

            return $date;
        } else {
            return '';
        }
    }
}

if (!function_exists('get_work_month')) {
    /**
     * @param $month
     * @return int
     */
    function get_work_month($month)
    {
        switch ($month) {
            case 10:
                return $month / 10;
            default:
                return 0;
        }
    }
}

if (!function_exists('rebuild_url')) {
    /**
     * 重新组装生成url
     * @param $url
     * @param $ext
     * @return string
     */
    function rebuild_url($url, $ext)
    {
        $urlBase = str_replace('.html', '', $url);
        return $urlBase . '/' . $ext . '.html';
    }
}

if (!function_exists('array_group_by')) {
    /**
     * 对二维数组进行分组
     * @param $arr
     * @param $key
     * @return array
     */
    function array_group_by($arr, $key)
    {
        $grouped = [];
        foreach ($arr as $value) {
            $grouped[$value[$key]][] = $value;
        }

        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $param = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $param);
            }
        }
        return $grouped;
    }
}

if (!function_exists('array_sort_by')) {
    /**
     * 数组排序
     * @param $arr
     * @param $key
     * @param string $type
     * @return array
     */
    function array_sort_by($arr, $key, $type = 'asc')
    {
        $keyValue = [];
        foreach ($arr as $k => $value) {
            $keyValue[$k] = $value[$key];
        }
        if ($type == 'asc') {
            asort($keyValue);
        } else {
            arsort($keyValue);
        }
        reset($keyValue);

        $sortData = [];
        foreach ($keyValue as $k => $value) {
            $sortData[$k] = $arr[$k];
        }
        return $sortData;
    }
}

if (!function_exists('build_complex_query_fields')) {
    /**
     * 构建复杂查询字段
     * @param array $fields
     * @param string $sep 模块与字段的分隔符
     * @return array
     */
    function build_complex_query_fields(array $fields, $sep = "__")
    {
        $newFields = [];
        foreach ($fields as $key => &$field) {
            $explodeField = explode('.', $field);
            if (count($explodeField) > 1) {
                $newFields[] = "{$field} AS {$explodeField[0]}{$sep}{$explodeField[1]}";
            }
        }
        return $newFields;
    }
}

if (!function_exists('separate_complex_query_data')) {
    /**
     * 分离复杂查询的数据
     * @param $data
     * @param string $sep
     * @param string $mainTable
     * @return array
     */
    function separate_complex_query_data($data, string $sep = "__", string $mainTable = '')
    {
        $newData = [];
        foreach ($data as $key => $value) {
            $explodeField = explode($sep, $key);
            if (count($explodeField) > 1 && $explodeField[0] !== $mainTable) {
                $newData[$explodeField[0]][$explodeField[1]] = $value;
            } else if (count($explodeField) > 1 && $explodeField[0] === $mainTable) {
                $newData[$explodeField[1]] = $value;
            } else {
                $newData[$key] = $value;
            }
        }
        return $newData;
    }
}

if (!function_exists('format_exception_info')) {
    /**
     * 格式化异常信息
     * @param $e
     * @return string
     */
    function format_exception_info($e)
    {
        return sprintf("%s:%d  %s\r\n%s", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getTraceAsString());
    }
}

if (!function_exists('build_queue_data_with_xu')) {
    /**
     * 生成一个队列数据 包含用户头信息
     * @param $data
     * @return false|string
     */
    function build_queue_data_with_xu($data)
    {
        if (!isset($data['xu'])) {
            $data['xu'] = request()->getXUserInfo();
        }
        return json_encode($data);
    }
}

if (!function_exists('get_random_str')) {
    /**
     * 获得随机字符串
     * @param $length
     * @return string
     * @throws Exception
     */
    function get_random_str($length = 8)
    {
        $strMap = [
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        ];
        $result = [];
        $maxIndex = count($strMap) - 1;
        for ($index = 0; $index < $length; $index++) {
            $result[] = $strMap[random_int(0, $maxIndex)];
        }
        return implode('', $result);
    }
}

if (!function_exists('teamones_request')) {

    /**
     * 服务内部请求
     * @param string $serviceName
     * @param string $route
     * @param $data
     * @param array $headers
     * @param bool $autoXu
     * @param string $method
     * @return array
     */
    function teamones_request(string $serviceName, string $route, $data, array $headers = [], bool $autoXu = true, string $method = 'POST'): array
    {
        $r = teamones\Request::connection();
        if ($autoXu) {
            $headers['X-Userinfo'] = request()->getXUserInfo();
        }
        $r->setMethod($method)
            ->setHeader($headers)
            ->setServerHost($serviceName)
            ->setRoute($route);
        if (isset($data)) {
            $r->setBody($data);
        }
        return $r->request();
    }
}

if (!function_exists('get_default_page')) {
    /**
     * 查询默认分页
     * @param $param
     * @return array
     */
    function get_default_page($param): array
    {
        if (empty($param['page'])) {
            return [1, C('database.database_max_select_rows')];
        }
        if ($param['page'][1] > C('database.database_max_select_rows')) {
            throw new \common\exception\LogicException('max query rows is ' . C('database.database_max_select_rows'), \support\ErrorCode::EXCEEDED_MAXIMUM_PAGE_NUM);
        }
        return $param['page'];
    }
}

if (!function_exists('rollback_parser_filter')) {
    /**
     * 处理过滤条件中的方法名
     * @param $data
     * @return mixed
     */
    function rollback_parser_filter($data)
    {
        if ((array_key_exists("param", $data) && array_key_exists("filter", $data['param'])) || array_key_exists("filter", $data)) {
            array_walk_recursive($data, 'rollback_parser_filter_condition');
        }
        return $data;
    }
}

if (!function_exists('rollback_parser_filter_condition')) {

    /**
     * 替换过滤条件中的方法名
     * @param $val
     * @param $key
     */
    function rollback_parser_filter_condition(&$val, $key)
    {
        $map = [
            'OR' => '-or',
            'AND' => '-and',
            'EQ' => '-eq',
            'NEQ' => '-neq',
            'GT' => '-gt',
            'EGT' => '-egt',
            'LT' => '-lt',
            'ELT' => '-elt',
            'LIKE' => '-lk',
            'NOTLIKE' => '-not-lk',
            'BETWEEN' => '-bw',
            'NOT BETWEEN' => '-not-bw',
            'IN' => '-in',
            'NOT IN' => '-not-in',
            'FIND_IN_SET' => '-fit',
        ];

        if (array_key_exists($val, $map)) {
            $val = $map[$val];
        }
    }
}
